const express = require('express');
const router = express.Router();
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

// 列出所有商品价格
router.get('/list', async (req, res) => {
  try {
    const { productName } = req.query;
    
    // 1. 获取所有商品（或指定商品）
    const whereClause = productName 
      ? { status: true, name: { contains: productName } }
      : { status: true };
    
    const products = await prisma.product.findMany({
      where: whereClause,
      orderBy: { name: 'asc' }
    });
    
    if (products.length === 0) {
      return res.json({ success: true, message: '没有找到符合条件的商品', data: [] });
    }
    
    // 2. 获取所有渠道
    const channels = await prisma.channel.findMany({
      where: { status: true },
      orderBy: { name: 'asc' }
    });
    
    // 3. 获取每个商品的价格信息
    const result = [];
    
    for (const product of products) {
      // 查找该商品的所有渠道价格
      const prices = await prisma.productPrice.findMany({
        where: { productId: product.id }
      });
      
      // 创建价格映射，方便查询
      const priceMap = {};
      prices.forEach(price => {
        priceMap[price.channelId] = price.price;
      });
      
      // 构建商品价格信息
      const productPrices = {
        productId: product.id,
        productName: product.name,
        standardPrice: product.price,
        channelPrices: channels.map(channel => ({
          channelId: channel.id,
          channelName: channel.name,
          price: priceMap[channel.id] !== undefined ? priceMap[channel.id] : null
        }))
      };
      
      result.push(productPrices);
    }
    
    return res.json({ 
      success: true, 
      message: '查询成功', 
      data: {
        products: result,
        channels: channels
      }
    });
  } catch (error) {
    console.error('查询商品价格出错:', error);
    return res.status(500).json({ success: false, message: '查询商品价格出错', error: error.message });
  }
});

// 设置指定商品在所有渠道的价格
router.post('/set-price', async (req, res) => {
  try {
    const { productId, price } = req.body;
    
    if (!productId || price === undefined) {
      return res.status(400).json({ success: false, message: '商品ID和价格不能为空' });
    }
    
    // 1. 查找商品
    const product = await prisma.product.findUnique({
      where: { id: productId }
    });
    
    if (!product) {
      return res.status(404).json({ success: false, message: '未找到指定商品' });
    }
    
    // 2. 查找所有渠道
    const channels = await prisma.channel.findMany({
      where: { status: true }
    });
    
    // 3. 设置商品在所有渠道的价格
    for (const channel of channels) {
      // 检查是否已存在价格记录
      const existingPrice = await prisma.productPrice.findUnique({
        where: {
          productId_channelId: {
            productId: product.id,
            channelId: channel.id
          }
        }
      });
      
      if (existingPrice) {
        // 更新现有价格记录
        await prisma.productPrice.update({
          where: {
            productId_channelId: {
              productId: product.id,
              channelId: channel.id
            }
          },
          data: {
            price: parseFloat(price),
            discount: 1
          }
        });
      } else {
        // 创建新的价格记录
        await prisma.productPrice.create({
          data: {
            productId: product.id,
            channelId: channel.id,
            price: parseFloat(price),
            discount: 1
          }
        });
      }
    }
    
    return res.json({ 
      success: true, 
      message: `已将商品 "${product.name}" 在所有渠道的价格设置为 ${price} 元` 
    });
  } catch (error) {
    console.error('设置商品价格出错:', error);
    return res.status(500).json({ success: false, message: '设置商品价格出错', error: error.message });
  }
});

// 修复所有商品的渠道价格（统一为最低价格）
router.post('/fix-all-prices', async (req, res) => {
  try {
    // 1. 获取所有商品
    const products = await prisma.product.findMany({
      where: { status: true }
    });
    
    // 2. 获取所有渠道
    const channels = await prisma.channel.findMany({
      where: { status: true }
    });
    
    const results = [];
    
    // 3. 遍历每个商品
    for (const product of products) {
      const productResult = {
        productId: product.id,
        productName: product.name,
        channelUpdates: []
      };
      
      // 查找该商品的所有渠道价格
      const prices = await prisma.productPrice.findMany({
        where: { productId: product.id }
      });
      
      if (prices.length === 0) {
        // 为所有渠道创建价格记录，使用商品标准价格
        for (const channel of channels) {
          await prisma.productPrice.create({
            data: {
              productId: product.id,
              channelId: channel.id,
              price: product.price,
              discount: 1
            }
          });
          
          productResult.channelUpdates.push({
            channelId: channel.id,
            channelName: channel.name,
            oldPrice: null,
            newPrice: product.price,
            action: 'create'
          });
        }
      } else {
        // 查找最低价格作为统一价格
        const lowestPrice = Math.min(...prices.map(p => p.price));
        
        // 确保每个渠道都有价格记录，并且价格一致
        for (const channel of channels) {
          const existingPrice = await prisma.productPrice.findUnique({
            where: {
              productId_channelId: {
                productId: product.id,
                channelId: channel.id
              }
            }
          });
          
          if (existingPrice) {
            // 如果价格不一致，更新为最低价格
            if (existingPrice.price !== lowestPrice) {
              await prisma.productPrice.update({
                where: {
                  productId_channelId: {
                    productId: product.id,
                    channelId: channel.id
                  }
                },
                data: {
                  price: lowestPrice,
                  discount: 1
                }
              });
              
              productResult.channelUpdates.push({
                channelId: channel.id,
                channelName: channel.name,
                oldPrice: existingPrice.price,
                newPrice: lowestPrice,
                action: 'update'
              });
            }
          } else {
            // 创建新的价格记录
            await prisma.productPrice.create({
              data: {
                productId: product.id,
                channelId: channel.id,
                price: lowestPrice,
                discount: 1
              }
            });
            
            productResult.channelUpdates.push({
              channelId: channel.id,
              channelName: channel.name,
              oldPrice: null,
              newPrice: lowestPrice,
              action: 'create'
            });
          }
        }
      }
      
      results.push(productResult);
    }
    
    return res.json({ 
      success: true, 
      message: '所有商品渠道价格修复完成', 
      data: results 
    });
  } catch (error) {
    console.error('修复价格出错:', error);
    return res.status(500).json({ success: false, message: '修复价格出错', error: error.message });
  }
});

module.exports = router; 